package com.qk.management.aop;

import cn.hutool.json.JSONUtil;
import com.qk.common.Result;
import com.qk.common.util.CurrentUserContextHolders;
import com.qk.entity.OperateLog;
import com.qk.management.mapper.OperateLogMapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Slf4j
@Aspect
@Component
public class LogRecordAspect {

    @Autowired
    private OperateLogMapper operateLogMapper;

    @Pointcut("@annotation(com.qk.management.aop.anno.LogAnno)")
    public void pt() {
    }


    @Around("pt()")
    public Object log(ProceedingJoinPoint pjp)  {

        Object returnValue = null;
        try {
            long startTime = System.currentTimeMillis();
            returnValue = pjp.proceed();
            long endTime = System.currentTimeMillis();

            Integer userId = CurrentUserContextHolders.get();

            String className = pjp.getTarget().getClass().getName();

            String methodName = pjp.getSignature().getName();

            Object[] args = pjp.getArgs();

            String params = JSONUtil.toJsonStr(args);

            String result = JSONUtil.toJsonStr(returnValue);

            OperateLog operateLog = OperateLog.builder()
                    .returnValue( result) // 返回值
                    .methodParams(params) // 参数
                    .methodName(methodName) // 方法名
                    .className( className) // 类名
                    .operateUserId(userId) // 操作人Id
                    .operateTime(LocalDateTime.now()) // 操作时间
                    .costTime(endTime - startTime) // 接口执行时间
                    .build() ;

            operateLogMapper.insert(operateLog);

        }catch (Throwable e){
            returnValue = Result.error("您的操作失败，请稍后重试！");
            log.error("操作失败:{}", e.getMessage());
        }
        return returnValue;
    }
}
